package edu.xidian.onlinedocument.utils.ot.json;

import com.alibaba.fastjson.JSONObject;
import edu.xidian.onlinedocument.utils.ot.internal.operations.Change;
import edu.xidian.onlinedocument.utils.ot.internal.operations.ChangesList;

import java.util.List;

/**
 * 传参对象：WebSocket连接的客户端
 * 传参内容：客户端通过WebSocket发送过来的操作序列ChangesList的JSON格式数据
 * 返回对象：WebSocket连接的服务端
 * 返回内容：本地存储的数据结构ChangesList
 */
public class FromJSON {
    private FromJSON() {}

    public static ChangesList fromJSONToChangesList(JSONObject object) {
        // 关于fastJSON的问题，如果直接用JSONObject.parseObject(object.toJSONString(), ChangeJSON.class)的话
        // 得到的ChangeJSON中的List是没有具体类的，当调用foreach方法的时候就会报错
        // 因此需要先调用JSONObject.parseArray实例化List对象
        List<ChangeJSON> changeJSONList = JSONObject.parseArray(object.getString("changeList"), ChangeJSON.class);
        int revision = object.getIntValue("revision");
        ChangesListJSON data = new ChangesListJSON(revision, changeJSONList);
        ChangesList list = fromChangesDataToChangesList(data);

        /*
        System.out.println("-----fromJSONToChangesList-----");
        System.out.println("-----from JSON-----");
        System.out.println(object);
        System.out.println("-----to ChangesList-----");
        System.out.println(list);
        System.out.println();
         */

        return list;
    }

    private static ChangesList fromChangesDataToChangesList(ChangesListJSON data) {
        ChangesList changesList = new ChangesList();
        Change change = null;

        int revision = data.getRevision();
        List<ChangeJSON> changeData = data.getChangeList();

        for (ChangeJSON d:
             changeData) {
            change = OperationClass.getChange(d);
            if(change != null) {
                changesList.addChange(change);
            }
        }
        changesList.setRevision(revision);
        return changesList;
    }
}
